<template>
  <div class="top" :style="{'--theme': theme}">
    <el-dialog
      ref="maxDialog"
      v-loading="loading"
      v-drag
      :title="title"
      :visible.sync="dialogVisible"
      width="450px"
    >
      <el-upload
        class="upload"
        drag
        action=""
        accept=".xls, .xlsx"
        :multiple="multiple"
        :show-file-list="false"
        :limit="limit"
        :file-list="fileList"
        :before-upload="beforeUpload"
        :http-request="httpRequest"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">
          只能上传xls/xlsx文件，且不超过10M
          <el-button v-permission="$route.meta.permission + ':' + 'download'" :size="size" type="text" class="download" @click="handlerDownload">点击下载模板</el-button>
        </div>
      </el-upload>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'ToChannel',
  props: {
    // 附加参数
    params: {
      type: Object,
      default: () => {}
    },
    // 弹窗标题
    title: {
      type: String,
      default: '导入'
    },
    // 上传是否为多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 上传最大个数
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      // 弹窗开关
      dialogVisible: false,
      // 加载开关
      loading: false,
      // 上传数组
      fileList: [],
      // 当前页面api函数对象
      funs: this.$store.state.settings.funs
    }
  },
  computed: {
    // 主题色
    theme() {
      return this.$store.state.settings.theme
    },
    size() {
      return this.$store.state.app.size
    }
  },
  methods: {
    // 选中文件后校验
    beforeUpload(file) {
      const isFile = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const isSize = file.size / 1024 / 1024 < 10

      if (!isFile) {
        this.$message.error('导入文件只能是xls/xlsx格式!')
      }
      if (!isSize) {
        this.$message.error('导入文件大小不能超过10MB!')
      }
      return isFile && isSize
    },
    // 自定义上传
    httpRequest(file) {
      const formData = new FormData()
      formData.append('file', file.file)
      if (this.params) {
        Object.keys(this.params).forEach(item => {
          formData.append(item, this.params[item])
        })
      }
      this.loading = true
      this.funs['imports'](formData).then(res => {
        this.dialogVisible = false
        this.fileList = []
        if (!res.data.errorCount) {
          this.$notify({
            title: '导入成功',
            message: `成功导入${res.data.count}条数据`,
            type: 'success'
          })
        } else {
          // 将base64转为blob最后转为临时文件
          const raw = window.atob(res.data.errorBase64)
          const rawLength = raw.length
          const uInt8Array = new Uint8Array(rawLength)
          for (let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i)
          }
          const blob = new Blob([uInt8Array])
          const url = URL.createObjectURL(blob)
          if (!res.data.count) {
            this.$notify({
              title: '导入失败',
              dangerouslyUseHTMLString: true,
              message: `<p>未导入${res.data.errorCount}条数据</p><p><a style="color: ${this.theme};text-decoration: underline;" href="${url}" download="${this.title}错误文件.xlsx">点击下载</a>&ensp;错误文件</p>`,
              type: 'error',
              duration: 0
            })
          } else if (res.data.errorCount) {
            this.$notify({
              title: '导入完成',
              dangerouslyUseHTMLString: true,
              message: `成功导入${res.data.count}条数据，未导入${res.data.errorCount}条数据<p><a style="color: ${this.theme};text-decoration: underline;" href="${url}" download="${this.title}错误文件.xlsx">点击下载</a>&ensp;错误文件</p>`,
              type: 'warning',
              duration: 0
            })
          }
        }
        this.$emit('change', {})
      }).finally(() => {
        this.loading = false
      })
    },
    // 模板下载
    handlerDownload() {
      this.loading = true
      this.funs['download']().then(res => {
        this.$download(res.data, this.$route.meta.title.replace('管理', '') + '导入模板.xlsx')
        this.$message({ type: 'success', message: '下载成功!' })
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>
<style scoped lang="scss">
  ::v-deep .upload .el-upload, ::v-deep .upload .el-upload-dragger {
    width: 100% !important;
  }

  .download {
    margin-left: 0.3rem;
    text-decoration: underline;
  }
</style>
